package com.s69.demo.service;

import com.s69.demo.dao.AppCategoryDao;
import com.s69.demo.entity.AppCategory;
import com.s69.demo.vo.CategoryTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryService {

    @Autowired
    AppCategoryDao appCategoryDao;


    public CategoryTreeVo tree() {
        List<CategoryTreeVo> voList = new ArrayList<>();
        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : list) {
            CategoryTreeVo vo = new CategoryTreeVo();
            BeanUtils.copyProperties(appCategory, vo);
            voList.add(vo);
        }



        CategoryTreeVo tree = new CategoryTreeVo();
        for (CategoryTreeVo vo : voList) {
            if (vo.getParentid() == null) {
                tree = findChildren(vo, voList);
            }
        }

        return tree;
    }

    private CategoryTreeVo findChildren(CategoryTreeVo vo, List<CategoryTreeVo> voList) {
        vo.setChildren(new ArrayList<>());
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (vo.getId() == categoryTreeVo.getParentid()) {
                vo.getChildren().add(categoryTreeVo);
                findChildren(categoryTreeVo, voList);
            }
        }
        return vo;
    }
}
